import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Modal } from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { RNCamera } from 'react-native-camera';
import Icon from 'react-native-vector-icons/Ionicons'; // 用于返回按钮的图标

interface IQRCodeScannerModalProps {
  modalVisible: boolean;
  onScanSuccess: (data: string) => void;
  onClose: () => void;
}

const QRCodeScannerModal: React.FC<IQRCodeScannerModalProps> = ({ modalVisible, onScanSuccess, onClose }) => {
  const [isScanning, setIsScanning] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsScanning(true);
    }, 1000);

    return () => clearTimeout(timer);
  }, []);

  // 扫描成功回调
  const handleScanSuccess = (e: any) => {
    if (isScanning) onScanSuccess(e.data);
  };

  return (
    <Modal animationType="slide" transparent={false} visible={modalVisible} onRequestClose={onClose}>
      <View style={styles.container}>
        <TouchableOpacity style={styles.backButton} onPress={onClose}>
          <Icon name="chevron-back-outline" size={28} color="#fff" />
        </TouchableOpacity>

        <QRCodeScanner
          onRead={handleScanSuccess}
          flashMode={RNCamera.Constants.FlashMode.auto}
          showMarker={true} // 显示扫描框
          bottomContent={<Text style={styles.centerText}>对准二维码/条码进行扫描</Text>}
          containerStyle={styles.scannerContainer}
        />
      </View>
    </Modal>
  );
};

// 样式
const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', backgroundColor: '#000' },
  scannerContainer: { flex: 1, justifyContent: 'center' },
  centerText: { fontSize: 16, color: '#fff', padding: 16, textAlign: 'center' },
  backButton: { position: 'absolute', top: 20, left: 10, zIndex: 10, padding: 10, backgroundColor: 'rgba(0,0,0,0.5)', borderRadius: 50 },
});

export default QRCodeScannerModal;
